import SparkMD5 from "spark-md5";

export function fileToBase64(file) {
  return new Promise((resolve, reject) => {
    const fileReader = new FileReader();
    fileReader.readAsDataURL(file);
    fileReader.onload = (ev) => {
      resolve(ev.target?.result);
    };
    fileReader.onerror = () => {
      console.error(new Error("something wrong!!"));
      reject("something wrong!!");
    };
  });
}

export function fileToBuffer(file) {
  return new Promise((resolve) => {
    const fileReader = new FileReader();
    fileReader.readAsArrayBuffer(file);
    fileReader.onload = (ev) => {
      let buffer = ev.target.result; // 得到文件二进制数据
      let spark = new SparkMD5.ArrayBuffer();
      spark.append(buffer);
      let HASH = spark.end(); // 通过文件数据得到一个 hash 值
      let suffix = /\.([a-zA-Z0-9]+)$/.exec(file.name)[1]; // 后缀名
      resolve({
        buffer,
        HASH,
        suffix,
        filename: `${HASH}.${suffix}`,
      });
    };
    fileReader.onerror = (err) => {
      console.error(err);
    };
  });
}

export function extractExt(filename) {
  return filename.slice(filename.lastIndexOf("."), filename.length);
}
